package org.dlx.drpc.simple;

import org.dlx.drpc.common.ExpRequest;
import org.dlx.drpc.common.ExpResponse;
import org.dlx.drpc.common.JsonDecoder;
import org.dlx.drpc.common.JsonEncoder;
import org.dlx.drpc.core.client.RPCClient;
import org.dlx.drpc.core.client.RPCConn;
import org.dlx.drpc.core.client.RPCPool;


import java.util.concurrent.CountDownLatch;


public class DemoClient
{
    public static void main(String[] args) {
        RPCClient client = new RPCClient("127.0.0.1", 8080, new JsonEncoder(), new JsonDecoder());
        try{
            client.start();
            RPCConn conn = client.newConn();
            int i = 0;
            for(; i < 5; i++) {
                ExpResponse re = client.send(conn, new ExpRequest(2, i), ExpResponse.class, 500000);
                System.out.printf("exp2(%d) = %d cost=%dns\n", i, re.getValue(), re.getCostInNanos());
            }
            conn.close();
            for(; i < 10; i++) {
                ExpResponse re = client.send(new ExpRequest(2, i), ExpResponse.class, 5000);
                System.out.printf("exp2(%d) = %d cost=%dns\n", i, re.getValue(), re.getCostInNanos());
            }

            RPCPool pool = new RPCPool(client);
            CountDownLatch cd = new CountDownLatch(10);
            for(; i<20;i++){
                final int j = i;
                new Thread(()->{
                    try{
                        ExpResponse re = pool.send(new ExpRequest(2, j), ExpResponse.class, 500000);
                        System.out.printf("exp2(%d) = %d cost=%dns\n", j, re.getValue(), re.getCostInNanos());
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                    finally
                    {
                        cd.countDown();
                    }
                }).run();
            }
            cd.await();
            pool.close();
        }catch (Exception e){
            e.printStackTrace();
        }


    }
}
